import { apiService } from './api';

// 数据同步相关类型定义
export interface DataSync {
  id: string;
  name: string;
  description?: string;
  type: 'manual' | 'scheduled' | 'realtime';
  status: 'enabled' | 'disabled';
  sourceSystem: string;
  targetSystem: string;
  syncRule: string;
  fieldMapping: Record<string, string>;
  schedule?: string; // cron表达式
  lastSyncTime?: string;
  nextSyncTime?: string;
  syncCount: number;
  successCount: number;
  failureCount: number;
  createdTime: string;
  updatedTime: string;
  createdBy: string;
  tenantId: string;
}

export interface DataSyncLog {
  id: string;
  syncId: string;
  syncName: string;
  status: 'running' | 'success' | 'failed';
  startTime: string;
  endTime?: string;
  duration?: number;
  recordCount: number;
  successCount: number;
  failureCount: number;
  errorMessage?: string;
  details?: string;
}

export interface DataSyncQueryParams {
  page?: number;
  size?: number;
  type?: string;
  status?: string;
  sourceSystem?: string;
  targetSystem?: string;
  keyword?: string;
  startDate?: string;
  endDate?: string;
}

export interface DataSyncCreateRequest {
  name: string;
  description?: string;
  type: 'manual' | 'scheduled' | 'realtime';
  sourceSystem: string;
  targetSystem: string;
  syncRule: string;
  fieldMapping: Record<string, string>;
  schedule?: string;
}

export interface DataSyncUpdateRequest {
  name?: string;
  description?: string;
  type?: 'manual' | 'scheduled' | 'realtime';
  sourceSystem?: string;
  targetSystem?: string;
  syncRule?: string;
  fieldMapping?: Record<string, string>;
  schedule?: string;
  status?: 'enabled' | 'disabled';
}

export interface SyncExecutionResult {
  success: boolean;
  message: string;
  recordCount: number;
  successCount: number;
  failureCount: number;
  duration: number;
  errors?: string[];
}

// 数据同步服务类
class DataSyncService {
  // 获取数据同步配置列表
  async getDataSyncs(params?: DataSyncQueryParams): Promise<{
    content: DataSync[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/data-sync', params);
  }

  // 获取数据同步配置详情
  async getDataSync(id: string): Promise<DataSync> {
    return apiService.get(`/data-sync/${id}`);
  }

  // 创建数据同步配置
  async createDataSync(dataSync: DataSyncCreateRequest): Promise<DataSync> {
    return apiService.post('/data-sync', dataSync);
  }

  // 更新数据同步配置
  async updateDataSync(id: string, dataSync: DataSyncUpdateRequest): Promise<DataSync> {
    return apiService.put(`/data-sync/${id}`, dataSync);
  }

  // 删除数据同步配置
  async deleteDataSync(id: string): Promise<void> {
    return apiService.delete(`/data-sync/${id}`);
  }

  // 批量删除数据同步配置
  async batchDeleteDataSyncs(ids: string[]): Promise<void> {
    return apiService.post('/data-sync/batch-delete', { ids });
  }

  // 启用数据同步
  async enableDataSync(id: string): Promise<DataSync> {
    return apiService.post(`/data-sync/${id}/enable`);
  }

  // 禁用数据同步
  async disableDataSync(id: string): Promise<DataSync> {
    return apiService.post(`/data-sync/${id}/disable`);
  }

  // 手动执行数据同步
  async executeDataSync(id: string): Promise<SyncExecutionResult> {
    return apiService.post(`/data-sync/${id}/execute`);
  }

  // 测试数据同步连接
  async testDataSyncConnection(id: string): Promise<{
    success: boolean;
    message: string;
    sourceConnected: boolean;
    targetConnected: boolean;
  }> {
    return apiService.post(`/data-sync/${id}/test-connection`);
  }

  // 验证数据同步配置
  async validateDataSyncConfig(config: DataSyncCreateRequest): Promise<{
    valid: boolean;
    errors: string[];
    warnings: string[];
  }> {
    return apiService.post('/data-sync/validate', config);
  }

  // 获取数据同步日志列表
  async getDataSyncLogs(syncId?: string, params?: {
    page?: number;
    size?: number;
    status?: string;
    startDate?: string;
    endDate?: string;
  }): Promise<{
    content: DataSyncLog[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    const url = syncId ? `/data-sync/${syncId}/logs` : '/data-sync-logs';
    return apiService.get(url, params);
  }

  // 获取数据同步日志详情
  async getDataSyncLog(id: string): Promise<DataSyncLog> {
    return apiService.get(`/data-sync-logs/${id}`);
  }

  // 获取数据同步统计信息
  async getDataSyncStatistics(): Promise<{
    total: number;
    enabled: number;
    disabled: number;
    totalExecutions: number;
    successExecutions: number;
    failedExecutions: number;
    successRate: number;
    avgDuration: number;
  }> {
    return apiService.get('/data-sync/statistics');
  }

  // 获取支持的系统列表
  async getSupportedSystems(): Promise<{
    id: string;
    name: string;
    type: 'database' | 'api' | 'file' | 'message_queue';
    description: string;
    configSchema: Record<string, any>;
  }[]> {
    return apiService.get('/data-sync/supported-systems');
  }

  // 获取字段映射建议
  async getFieldMappingSuggestions(sourceSystem: string, targetSystem: string): Promise<{
    sourceFields: string[];
    targetFields: string[];
    suggestedMappings: Record<string, string>;
  }> {
    return apiService.get('/data-sync/field-mapping-suggestions', {
      sourceSystem,
      targetSystem
    });
  }

  // 预览同步数据
  async previewSyncData(id: string, limit: number = 10): Promise<{
    sourceData: Record<string, any>[];
    targetData: Record<string, any>[];
    mappedData: Record<string, any>[];
  }> {
    return apiService.get(`/data-sync/${id}/preview`, { limit });
  }

  // 获取同步进度
  async getSyncProgress(id: string): Promise<{
    status: 'running' | 'completed' | 'failed';
    progress: number;
    currentStep: string;
    totalRecords: number;
    processedRecords: number;
    successRecords: number;
    failedRecords: number;
    startTime: string;
    estimatedEndTime?: string;
  }> {
    return apiService.get(`/data-sync/${id}/progress`);
  }

  // 停止正在运行的同步
  async stopDataSync(id: string): Promise<void> {
    return apiService.post(`/data-sync/${id}/stop`);
  }

  // 重试失败的同步
  async retryDataSync(logId: string): Promise<SyncExecutionResult> {
    return apiService.post(`/data-sync-logs/${logId}/retry`);
  }

  // 导出同步配置
  async exportDataSyncConfig(id: string): Promise<Blob> {
    const response = await apiService.get<Blob>(`/data-sync/${id}/export`, {}, {
      responseType: 'blob'
    });
    return response as Blob;
  }

  // 导入同步配置
  async importDataSyncConfig(file: File): Promise<DataSync> {
    const formData = new FormData();
    formData.append('file', file);
    return apiService.post<DataSync>('/data-sync/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
}

export const dataSyncService = new DataSyncService();